function restHandle(data) {
    if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
        var code = parseInt(data.substring(0, 3));
        // TODO : stylize depending rest code type
        result = (data.substring(4, data.length));
        if (result.charAt(result.length - 1) == '§') {
            return result.substring(0, result.length - 1).replace('§', '');
        }
    }
    return data;
}

function getRest(data) {
    if (data != undefined) {
        if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
            var code = parseInt(data.substring(0, 3));
            data = data.replace(code + '§', '');
            var message = (data.substring(0, data.indexOf('§')));
            message = message.replace('§', '');
            return {
                'code': parseInt(code),
                'message': message
            };
        }
    }
    return {
        'code': 0,
        'message': ''
    };
}

function getResponse(data) {
    if (data != undefined) {
        if (data.length >= 4 && parseInt(data.substring(0, 3)) > 0 && data.charAt(3) == '§') {
            var code = parseInt(data.substring(0, 3));
            data = data.replace(code + '§', '');
            var message = (data.indexOf('§') + 1 < data.length) ? (data.substring(data.indexOf('§') + 1, data.length)) : '';
            return message;
        }
    }
    return '';
}


function ajax(url, post_array, success, doneFunction) {

    if (typeof ajaxRequest == 'object') {
        ajaxRequest.abort();
    }
    $('.ajax-loader').show();
    ajaxRequest = $.ajax({
        url: url,
        data: post_array,
        type: 'post',
        success: function(data) {
            RUNNING_REQUEST = false;
            success(data);
            $('.ajax-loader').hide();
        }
    }).done(function() {
        if (typeof(doneFunction) == "function") {
            doneFunction();
        }
    });
}


function ajaxForce(url, post_array, success, doneFunction) {
    $('.ajax-loader').show();
    $.ajax({
        url: url,
        data: post_array,
        type: 'post',
        success: function(data) {
            RUNNING_REQUEST = false;
            success(data);
            $('.ajax-loader').hide();
        }
    }).done(function() {
        if (typeof(doneFunction) == "function") {
            doneFunction();
        }
    });
}

function bErrors(field_list) {
    var bErrorExist = false;
    for (var i = 0; i < field_list.length; i++) {
        if (field_list[i].data('bError') == true) {
            bErrorExist = true;
        }
    }
    return bErrorExist;
}

function setError($item, error_message) {
    removeError($item);
    $item.css('style', 'border: 1px solid red;');
    $item.before('<div class="erra-form-common-field_error">' + error_message + '</div>');

    $item.data('bError', true);
}

function removeError($element) {
    if ($element.length) {
        $element.removeAttr('style');
        if ($element.prev('div').hasClass('erra-form-common-field_error')) {
            $element.prev('div').remove();
        }
        $element.data('bError', false);
    }
}


function ajax_form_reset($form) {
    if ($form.find('input:text, input:password, input:file, textarea').length)
        $form.find('input:text, input:password, input:file, textarea').val('');
    if ($form.find('select').removeAttr('selected').length)
        $form.find('select').removeAttr('selected').val('');

    if ($form.find('input:checkbox, input:radio').length)
        $form.find('input:checkbox, input:radio').removeAttr('checked');

    if ($form.find('.ajax-error-message').length)
        $form.find('.ajax-error-message').remove();
}

function ctype_alnum(checkString) {
    var regExp = /^[A-Za-z0-9]+$/;
    if (checkString.match(regExp) != null) {
        return true;
    } else {
        return false;
    }
}


function is_numeric(mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: David
    // +   improved by: taith
    // +   bugfixed by: Tim de Koning
    // +   bugfixed by: WebDevHobo (http://webdevhobo.blogspot.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    // *     example 4: is_numeric([]);
    // *     returns 4: false
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function uniqid(prefix, more_entropy) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kankrelune (http://www.webfaktory.info/)
    // %        note 1: Uses an internal counter (in php_js global) to avoid collision
    // *     example 1: uniqid();
    // *     returns 1: 'a30285b160c14'
    // *     example 2: uniqid('foo');
    // *     returns 2: 'fooa30285b1cd361'
    // *     example 3: uniqid('bar', true);
    // *     returns 3: 'bara20285b23dfd1.31879087'
    if (typeof prefix == 'undefined') {
        prefix = "";
    }

    var retId;
    var formatSeed = function(seed, reqWidth) {
        seed = parseInt(seed, 10).toString(16); // to hex str
        if (reqWidth < seed.length) { // so long we split
            return seed.slice(seed.length - reqWidth);
        }
        if (reqWidth > seed.length) { // so short we pad
            return Array(1 + (reqWidth - seed.length)).join('0') + seed;
        }
        return seed;
    };

    // BEGIN REDUNDANT
    if (!this.php_js) {
        this.php_js = {};
    }
    // END REDUNDANT
    if (!this.php_js.uniqidSeed) { // init seed with big random int
        this.php_js.uniqidSeed = Math.floor(Math.random() * 0x75bcd15);
    }
    this.php_js.uniqidSeed++;

    retId = prefix; // start with prefix, add current milliseconds hex string
    retId += formatSeed(parseInt(new Date().getTime() / 1000, 10), 8);
    retId += formatSeed(this.php_js.uniqidSeed, 5); // add seed hex string
    if (more_entropy) {
        // for more entropy we add a float lower to 10
        retId += (Math.random() * 10).toFixed(8).toString();
    }

    return retId;
}

function timestamp_to_hybrid_date(timestamp) {
    if (timestamp < 10000000000) {
        timestamp = timestamp * 1000;
    }
    var today = new Date(timestamp);
    today.setHours(0);
    today.setMinutes(0);
    today.setSeconds(0);
    return pad2(today.getDate()) + '-' + pad2(today.getMonth() + 1) + '-' + today.getFullYear();
}

function pad2(number) {
    return (number < 10 ? '0' : '') + number

}

function is_french_phone(num_tel)
{
    var isnum = /^\d+$/.test(num_tel);
    return (isnum && num_tel.length == 10) ? true : false;
}

function empty(mixed_var) {
    // Checks if the argument variable is empty
    // undefined, null, false, number 0, empty string,
    // string "0", objects without properties and empty arrays
    // are considered empty
    //
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +      input by: Stoyan Kyosev (http://www.svest.org/)
    // +   improved by: Rafal Kukawski
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    var undef, key, i, len;
    var emptyValues = [undef, null, false, 0, "", "0"];

    for (i = 0, len = emptyValues.length; i < len; i++) {
        if (mixed_var === emptyValues[i]) {
            return true;
        }
    }

    if (typeof mixed_var === "object") {
        for (key in mixed_var) {
            // TODO: should we check for own properties only?
            //if (mixed_var.hasOwnProperty(key)) {
            return false;
            //}
        }
        return true;
    }

    return false;
}

function erraAlert(message) {
    $('#message').html(message);
    $("#message").dialog({
        closeOnEscape: false,
        open: function(event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
        width: 400,
        modal: true,
        buttons: {
            "OK": function() {
                $('#message').dialog('close');
            }
        }
    });
}

function each($collection, exec) {
    if ($collection.length) {
        for (var i = 0, len = $collection.length; i < len; i++) {
            exec($($collection[i]));
        }
    }
}


function extractNumbers(str) {
    var m = /\d+\.?\d*/g.exec(str);
    return m;
}


function erraAlertModal(message, extraFunction) {
    $('#message').html(message);
    $("#message").dialog({
        width: 500,
        modal: true,
        buttons: {
            "OK": function() {
                $('#message').dialog('close');
                extraFunction();
            }
        }
    });
}
function json_decode(str_json) {
    // http://kevin.vanzonneveld.net
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      improved by: T.J. Leahy
    // +      improved by: Michael White
    // *        example 1: json_decode('[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]');
    // *        returns 1: ['e', {pluribus: 'unum'}]
    /*
     http://www.JSON.org/json2.js
     2008-11-19
     Public Domain.
     NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
     See http://www.JSON.org/js.html
     */

    var json = this.window.JSON;
    if (typeof json === 'object' && typeof json.parse === 'function') {
        try {
            return json.parse(str_json);
        } catch (err) {
            if (!(err instanceof SyntaxError)) {
                throw new Error('Unexpected error type in json_decode()');
            }
            this.php_js = this.php_js || {};
            this.php_js.last_error_json = 4; // usable by json_last_error()
            return null;
        }
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var j;
    var text = str_json;

    // Parsing happens in four stages. In the first stage, we replace certain
    // Unicode characters with escape sequences. JavaScript handles many characters
    // incorrectly, either silently deleting them, or treating them as line endings.
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function(a) {
            return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }

    // In the second stage, we run the text against regular expressions that look
    // for non-JSON patterns. We are especially concerned with '()' and 'new'
    // because they can cause invocation, and '=' because it can cause mutation.
    // But just to be safe, we want to reject all unexpected forms.
    // We split the second stage into 4 regexp operations in order to work around
    // crippling inefficiencies in IE's and Safari's regexp engines. First we
    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
    // replace all simple value tokens with ']' characters. Third, we delete all
    // open brackets that follow a colon or comma or that begin the text. Finally,
    // we look to see that the remaining characters are only whitespace or ']' or
    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
    if ((/^[\],:{}\s]*$/).
            test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
            replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
            replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        // In the third stage we use the eval function to compile the text into a
        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
        // in JavaScript: it can begin a block or an object literal. We wrap the text
        // in parens to eliminate the ambiguity.
        j = eval('(' + text + ')');

        return j;
    }

    this.php_js = this.php_js || {};
    this.php_js.last_error_json = 4; // usable by json_last_error()
    return null;
}

function implode(glue, pieces) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '',
            retVal = '',
            tGlue = '';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (Object.prototype.toString.call(pieces) === '[object Array]') {
            return pieces.join(glue);
        }
        for (i in pieces) {
            retVal += tGlue + pieces[i];
            tGlue = glue;
        }
        return retVal;
    }
    return pieces;
}



function erraAlertOK(message, extraFunction) {
    $('#message').html(message);
    $("#message").dialog({
        width: 400,
        modal: true,
        position: 'center',
        buttons: {
            "OK": function() {
                extraFunction();
            },
            "Annuler": function() {
                $(this).dialog("close");
            }
        }
    });
}